<template>
  <div class="emergency-drill-page">
    <!-- 查询表单 -->
    <el-card class="query-card" shadow="never">
      <el-form :model="queryForm" inline>
        <el-form-item label="演练名称">
          <el-input
            v-model="queryForm.drillName"
            placeholder="请输入演练名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="演练类型">
          <el-select
            v-model="queryForm.drillType"
            placeholder="请选择演练类型"
            clearable
            style="width: 150px"
          >
            <el-option label="桌面演练" value="desktop" />
            <el-option label="功能演练" value="functional" />
            <el-option label="全面演练" value="comprehensive" />
            <el-option label="实战演练" value="actual" />
            <el-option label="其他演练" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="演练状态">
          <el-select
            v-model="queryForm.status"
            placeholder="请选择演练状态"
            clearable
            style="width: 120px"
          >
            <el-option label="计划中" value="planning" />
            <el-option label="准备中" value="preparing" />
            <el-option label="进行中" value="ongoing" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="演练日期">
          <el-date-picker
            v-model="queryForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card class="operation-card" shadow="hover">
      <el-row :gutter="10">
        <el-col :span="24">
          <el-button type="primary" plain :icon="Plus" @click="handleAdd">新增演练</el-button>
          <el-button
            type="danger"
            plain
            :icon="Delete"
            :disabled="!selectedRows.length"
            @click="handleBatchDelete"
          >
            批量删除
          </el-button>
          <el-button type="success" plain :icon="Download" @click="handleExport">导出数据</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="hover">
      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="drillCode" label="演练编号" width="120" />
        <el-table-column prop="drillName" label="演练名称" min-width="200" />
        <el-table-column prop="drillType" label="演练类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.drillType)">
              {{ getTypeText(row.drillType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="level" label="演练级别" width="100">
          <template #default="{ row }">
            <el-tag :type="getLevelTagType(row.level)">
              {{ getLevelText(row.level) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="organizer" label="组织单位" width="120" />
        <el-table-column prop="participants" label="参与人数" width="100" />
        <el-table-column prop="drillDate" label="演练日期" width="120" />
        <el-table-column prop="duration" label="演练时长" width="100" />
        <el-table-column prop="status" label="演练状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="演练评分" width="100" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link :icon="Edit" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="info" link :icon="View" @click="handleView(row)">
              查看
            </el-button>
            <el-button type="success" link :icon="VideoPlay" @click="handleStart(row)">
              开始
            </el-button>
            <el-button type="danger" link :icon="Delete" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <Pagination
          v-model:page="pagination.currentPage"
          v-model:limit="pagination.pageSize"
          :total="pagination.total"
          @pagination="handlePagination"
        />
      </div>
    </el-card>

    <!-- 表单弹窗 -->
    <EmergencyDrillFormDialog
      v-model:visible="dialogVisible"
      :form-data="currentRow"
      :is-view="isView"
      @success="handleDialogSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Download, Edit, View, VideoPlay } from '@element-plus/icons-vue'
import EmergencyDrillFormDialog from './components/EmergencyDrillFormDialog.vue'
import Pagination from '@/components/Pagination/index.vue'

// 查询表单
const queryForm = reactive({
  drillName: '',
  drillType: '',
  status: '',
  dateRange: []
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedRows = ref([])

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 弹窗相关
const dialogVisible = ref(false)
const currentRow = ref(null)
const isView = ref(false)

// 获取类型标签样式
const getTypeTagType = (type: string) => {
  const typeMap = {
    'desktop': 'info',
    'functional': 'primary',
    'comprehensive': 'warning',
    'actual': 'danger',
    'other': 'success'
  }
  return typeMap[type] || 'info'
}

// 获取类型文本
const getTypeText = (type: string) => {
  const typeMap = {
    'desktop': '桌面演练',
    'functional': '功能演练',
    'comprehensive': '全面演练',
    'actual': '实战演练',
    'other': '其他演练'
  }
  return typeMap[type] || type
}

// 获取级别标签样式
const getLevelTagType = (level: string) => {
  const levelMap = {
    'I': 'danger',
    'II': 'warning',
    'III': 'primary',
    'IV': 'success'
  }
  return levelMap[level] || 'info'
}

// 获取级别文本
const getLevelText = (level: string) => {
  const levelMap = {
    'I': 'I级',
    'II': 'II级',
    'III': 'III级',
    'IV': 'IV级'
  }
  return levelMap[level] || level
}

// 获取状态标签样式
const getStatusTagType = (status: string) => {
  const statusMap = {
    planning: 'info',
    preparing: 'warning',
    ongoing: 'primary',
    completed: 'success',
    cancelled: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap = {
    planning: '计划中',
    preparing: '准备中',
    ongoing: '进行中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

// 数据源与工具函数
const allData = ref<any[]>([])
const randInt = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min
const randomChoice = <T>(arr: T[]) => arr[Math.floor(Math.random() * arr.length)]

const generateMockData = (count: number) => {
  const types = ['desktop', 'functional', 'comprehensive', 'actual', 'other']
  const levels = ['I', 'II', 'III', 'IV']
  const statuses = ['planning', 'preparing', 'ongoing', 'completed', 'cancelled']
  const organizers = ['应急管理部', '运维部', '调度中心', '安监办', '水政科']
  const locations = ['水库大坝', '机房', '调度中心', '值班室', '泵站', '闸门区']
  const commanders = ['张三', '李四', '王五', '赵六', '钱七', '孙八']
  const today = new Date()
  const data: any[] = []

  for (let i = 1; i <= count; i++) {
    const date = new Date(today.getTime() - randInt(0, 180) * 24 * 3600 * 1000)
    const dStr = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    const type = randomChoice(types)
    const level = randomChoice(levels)
    const status = randomChoice(statuses)

    data.push({
      id: i,
      drillCode: `ED${today.getFullYear()}${String(i).padStart(4, '0')}`,
      drillName: `${getTypeText(type)}-${i}`,
      drillType: type,
      level,
      organizer: randomChoice(organizers),
      participants: randInt(10, 100),
      drillDate: dStr,
      duration: `${randInt(1, 6)}小时`,
      status,
      score: status === 'completed' ? randInt(60, 100) : 0,
      location: randomChoice(locations),
      commander: randomChoice(commanders),
      phone: `138${String(randInt(10000000, 99999999))}`,
      email: 'noreply@example.com',
      objective: '提升应急处置能力',
      scenario: '模拟突发事件',
      process: '预警-响应-处置-评估',
      equipment: '通讯设备、抢险器材',
      evaluation: status === 'completed' ? '演练达到预期' : '',
      problems: '',
      improvements: '',
      remark: ''
    })
  }
  return data
}

const applyFiltersAndPaginate = () => {
  let filtered = allData.value.slice()
  if (queryForm.drillName) {
    const kw = queryForm.drillName.trim()
    filtered = filtered.filter(item => String(item.drillName).includes(kw))
  }
  if (queryForm.drillType) {
    filtered = filtered.filter(item => item.drillType === queryForm.drillType)
  }
  if (queryForm.status) {
    filtered = filtered.filter(item => item.status === queryForm.status)
  }
  if (Array.isArray(queryForm.dateRange) && queryForm.dateRange.length === 2 && queryForm.dateRange[0] && queryForm.dateRange[1]) {
    const [start, end] = queryForm.dateRange as [string, string]
    const startTime = new Date(start).getTime()
    const endTime = new Date(end).getTime()
    filtered = filtered.filter(item => {
      const t = new Date(item.drillDate).getTime()
      return t >= startTime && t <= endTime
    })
  }

  pagination.total = filtered.length
  const startIndex = (pagination.currentPage - 1) * pagination.pageSize
  tableData.value = filtered.slice(startIndex, startIndex + pagination.pageSize)
}

// 获取应急演练列表（分页切片）
const fetchEmergencyDrillList = async () => {
  loading.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 300))
    if (!allData.value.length) {
      allData.value = generateMockData(randInt(10, 50))
    }
    applyFiltersAndPaginate()
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 模拟API - 删除应急演练
const deleteEmergencyDrill = async (ids: number[]) => {
  try {
    await new Promise(resolve => setTimeout(resolve, 300))
    allData.value = allData.value.filter((item: any) => !ids.includes(item.id))
    ElMessage.success('删除成功')
    applyFiltersAndPaginate()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 模拟API - 开始演练
const startEmergencyDrill = async (id: number) => {
  try {
    await new Promise(resolve => setTimeout(resolve, 300))
    const item = allData.value.find((i: any) => i.id === id)
    if (item) item.status = 'ongoing'
    ElMessage.success('演练已开始')
    applyFiltersAndPaginate()
  } catch (error) {
    ElMessage.error('开始演练失败')
  }
}

// 模拟API - 导出数据
const exportEmergencyDrill = async () => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// 查询
const handleQuery = () => {
  pagination.currentPage = 1
  applyFiltersAndPaginate()
}

// 重置
const handleReset = () => {
  Object.assign(queryForm, {
    drillName: '',
    drillType: '',
    status: '',
    dateRange: []
  })
  handleQuery()
}

// 新增
const handleAdd = () => {
  currentRow.value = null
  isView.value = false
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  currentRow.value = { ...row }
  isView.value = false
  dialogVisible.value = true
}

// 查看
const handleView = (row: any) => {
  currentRow.value = { ...row }
  isView.value = true
  dialogVisible.value = true
}

// 开始演练
const handleStart = (row: any) => {
  ElMessageBox.confirm('确定要开始这次应急演练吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    startEmergencyDrill(row.id)
  })
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确定要删除这次应急演练吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteEmergencyDrill([row.id])
  })
}

// 批量删除
const handleBatchDelete = () => {
  const ids = selectedRows.value.map((row: any) => row.id)
  ElMessageBox.confirm(`确定要删除选中的 ${ids.length} 次应急演练吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteEmergencyDrill(ids)
  })
}

// 导出
const handleExport = () => {
  exportEmergencyDrill()
}

// 表格选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 分页处理
const handlePagination = (page: any) => {
  pagination.currentPage = page.page
  pagination.pageSize = page.limit
  applyFiltersAndPaginate()
}

// 弹窗成功回调
const handleDialogSuccess = () => {
  fetchEmergencyDrillList()
}

// 初始化
onMounted(() => {
  fetchEmergencyDrillList()
})
</script>

<style scoped>
.emergency-drill-page {
  padding: 20px;
}

.query-card,
.operation-card,
.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>